package com.restaurant.application.levelset;

import com.google.common.base.Strings;
import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.base.data.ViewUpdate;
import com.nebutown.commonunits.dataface.DataModes;
import com.nebutown.commonunits.dataface.EntryTypes;
import com.nebutown.commonunits.dataface.FormShell;
import com.nebutown.commonunits.dataface.TableShell;
import com.nebutown.commonunits.dataface.definitions.*;
import com.nebutown.commonunits.uidataface.UIDataFace;
import com.nebutown.generation.basicdata.UIDRecord;
import com.nebutown.generation.basictype.StringData;
import com.nebutown.generation.basictype.UID;
import com.restaurant.application.level.Level;
import com.restaurant.application.level.support.LevelData;
import com.restaurant.application.levelset.support.AbstractLevelSet;
import com.restaurant.application.levelset.support.LevelSetPageData;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class LevelSetImpl extends AbstractLevelSet {
    @Override
    public ViewUpdate insert(int[] seq) {
        Level level = createNode(Level.class);
        return returnPushInContainer(level.getId(), false);
    }

    @Override
    public ViewUpdate search(LevelSetPageData search, int[] seq) {
        return returnView(newCommonTable(search, 1));
    }

    @Override
    public ViewUpdate detail(int[] seq) {
        return null;
    }

    @Override
    public ViewUpdate edit(int[] seq) {
        return null;
    }

    @Override
    public ViewUpdate delete(int[] seq) {
        getData().getLists().remove(seq[0]);
        return returnView(newCommonTable(new LevelSetPageData(), 1));
    }

    @Override
    public ViewUpdate switchPage(StringData switchPage, int[] seq) {
        return null;
    }

    @Override
    public View getFullView() {
        return newCommonTable(new LevelSetPageData(), 1);
    }

    @Override
    public View getViewLead(ViewSpec spec) {
        return null;
    }

    @Override
    public UID findLevel(int score) {
        return getData().getLists().getAll().stream()
                .sorted((x, y) -> Math.toIntExact(getUnit(Level.class, x.getUid()).findData().getScore() - getUnit(Level.class, y.getUid()).findData().getScore()))
                .filter(x -> getUnit(Level.class, x.getUid()).checkScore(score)
                ).findFirst().map(UIDRecord::getUid).orElse(null);
    }

    @Override
    public List<UID> findAllLevel() {
        return getData().getLists().getAll().stream().map(UIDRecord::getUid).collect(Collectors.toList());
    }

    @Override
    public void addLevel(UID id) {
        if (id != null) {
            getData().getLists().add(id);
        }
    }

    private View newCommonTable(LevelSetPageData search, int pageNum) {
        int pageSize = 10;
        List<UIDRecord> records = getData().getLists().getAll();
        int totalRecord = records.size();
        int totalPage = (totalRecord + pageSize + 1) / pageSize;
        List<UIDRecord> recordList = records.stream()
                .filter(e -> {
                    if (!Strings.isNullOrEmpty(search.getMemberName())) {
                        return getUnit(Level.class, e.getUid()).findData().getMemberName().contains(search.getMemberName());
                    }
                    return true;
                }).sorted(Comparator.comparing(x -> getUnit(Level.class, x.getUid()).findData().getModifyTime()))
                .skip(pageSize * (pageNum - 1))
                .limit(pageSize).collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo()
                .withPageNum(pageNum)
                .withPageSize(pageSize)
                .withTotalPage(totalPage)
                .withTotalRecord(totalRecord)
                .withJumpPath(getPath(CMD_SWITCHPAGE));
        PageForm pageForm = newFormShell(recordList, pageInfo).getForm();
        return getSingleton(UIDataFace.class).newGenericForm(unitPosition(), pageForm);
    }

    private FormShell newFormShell(List<UIDRecord> recordList, PageInfo pageInfo) {

        FormShell formShell = new FormShell("系统设置", 3, 3);

        formShell.source(new LevelSetPageData(), DataModes.EDIT);

        formShell.at(0, 0, "")
                .getEntry(LevelSetPageData.FN_MEMBERNAME, "")
                .placeHolder("")
                .simpleEntry(EntryTypes.STRING)
                .getContent().setEditable(true);

        formShell.at(0, 1, "搜索")
                .buttonField(getPath(CMD_SEARCH), "", true);
        formShell.at(0, 2, "新增")
                .buttonField(getPath(CMD_INSERT), "", false);

        List<LevelSetPageData> collect = recordList.stream().map(e -> {
            LevelData levelData = getUnit(Level.class, e.getUid()).findData();
            return new LevelSetPageData().withMemberLevel(levelData.getMemberLevel())
                    .withMemberName(levelData.getMemberName()).withScore(levelData.getScore())
                    .withSeq(Long.valueOf(e.getSeq()));
        }).collect(Collectors.toList());
        TableShell<LevelSetPageData> tableShell = new TableShell<>(LevelSetPageData.class, collect).withPageInfo(pageInfo);

        tableShell.createColumn(LevelSetPageData.FN_MEMBERLEVEL).withName("等级").cellCalculator(b -> {
            LevelSetPageData bean = (LevelSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getMemberLevel() == null ? "" : String.valueOf(bean.getMemberLevel())));
        });
        tableShell.createColumn(LevelSetPageData.FN_MEMBERNAME).withName("名称").cellCalculator(b -> {
            LevelSetPageData bean = (LevelSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getMemberName() == null ? "" : bean.getMemberName()));
        });
        tableShell.createColumn(LevelSetPageData.FN_SCORE).withName("所需积分").cellCalculator(b -> {
            LevelSetPageData bean = (LevelSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getScore() == null ? "" : String.valueOf(bean.getScore())));
        });
        tableShell.createColumn("doSomething").withName("操作").cellCalculator(b -> {
            LevelSetPageData bean = (LevelSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("查看").withButtonPath(getPath(CMD_DETAIL, bean.getSeq()))))
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("编辑").withButtonPath(getPath(CMD_EDIT, bean.getSeq()))))
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("删除").withButtonPath(getPath(CMD_DELETE, bean.getSeq()))));
        });

        formShell.at(2, 0, "系统设置")
                .large(3, 1)
                .getEntry("error", "")
                .tableEntry(tableShell);

        return formShell;
    }
}
